package cn.bitkit.mybatis.criteria;

import cn.bitkit.mybatis.SqlCommonHandler;
import cn.bitkit.mybatis.annotation.Query;
import cn.bitkit.mybatis.base.BaseCriteria;
import cn.bitkit.base.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.stream.Collectors;

/**
 * @author changbo
 */
@Slf4j
public class DynamicCriteria implements BaseCriteria {

    @Override
    public String getSql(Query query, String fieldName, Object fieldValue, String column) {
        if(fieldValue instanceof Collection<?> values){
            String sql =  values.stream().filter(StringUtil::hasValue)
                    .map(e -> "(" + StringUtil.getValue(e) + ")")
                    .collect(Collectors.joining(" and "));
            log.info("DynamicCompare:{}", sql);
            SqlCommonHandler.checkSql(sql);
            return sql;
        }
        if(StringUtil.hasValue(fieldValue)){
            String sql = StringUtil.getValue(fieldValue);
            log.info("DynamicCompare:{}", sql);
            SqlCommonHandler.checkSql(sql);
            return sql;
        }
        return null;
    }

}
